package com.ss.android.newmedia.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Base64;
import android.webkit.WebView;

import com.bytedance.article.common.c.TTUtils;
import com.bytedance.common.utility.Logger;
import com.bytedance.common.utility.NetworkType;
import com.bytedance.frameworks.baselib.network.http.exception.HttpResponseException;
import com.bytedance.frameworks.baselib.network.http.util.BuffHolder;
import com.bytedance.frameworks.baselib.network.http.util.TaskInfo;
import com.bytedance.frameworks.baselib.network.http.util.d;
import com.ss.android.common.app.permission.PermissionsManager;
import com.ss.android.common.applog.AppLog;
import com.ss.android.common.dialog.AlertDialog;
import com.ss.android.common.download.DownloadAdapterProxy;
import com.ss.android.common.lib.MobClickCombiner;
import com.ss.android.common.util.NetworkUtils;
import com.ss.android.common.util.ToolUtils;
import com.ss.android.http.legacy.HttpHeader;
import com.ss.android.http.legacy.a.LegacyHeader;
import com.ss.android.image.BaseImageManager;
import com.ss.android.image.model.ImageInfo;
import com.ss.android.image.model.ImageUrl;
import com.ss.android.newmedia.BaseAppData;
import com.ss.android.newmedia.MediaAppData;
import com.ss.android.newmedia.a.AdsAppBaseActivity;
import com.ss.android.newmedia.f.Response;
import com.ss.android.newmedia.MediaAppUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.zip.GZIPInputStream;

public final class AppUtil extends MediaAppUtil {
    public static boolean downloadImage(Context context,
                                        int arg19,
                                        String arg20,
                                        List<ImageUrl> imageUrlList,
                                        String externalImageSaveDir,
                                        String internalImageSaveDir,
                                        String cacheFileName,
                                        d arg25,
                                        String arg26,
                                        TaskInfo taskInfo) throws Throwable {
        long v4_1;
        boolean v14;
        boolean v2_1;
        int v2 = arg19 <= 0 ? 20971520 : arg19;
        if (imageUrlList != null && !imageUrlList.isEmpty()) {
            if (context == null) {
                context = sContext;
            }

            Iterator<ImageUrl> iterator = imageUrlList.iterator();
            int v5 = 0;
            while (true) {
                if (!iterator.hasNext()) {
                    return false;
                }

                ImageUrl imageUrl = iterator.next();
                if (imageUrl == null) {
                    continue;
                }

                String url = imageUrl.url;
                if (android.support.design.a.isTextEmpty(url)) {
                    continue;
                }

                int v13 = v5 + 1;
                if (v13 > 3) {
                    return false;
                }

                if (Logger.debug()) {
                    Logger.v("AppUtil", "try image: " + arg20 + " " + url);
                }

                String[] v11 = new String[1];
                int[] v12 = new int[1];
                long v16 = System.currentTimeMillis();
                if (context != null) {
                    try {
                        if (!NetworkUtils.isNetworkAvailable(context)) {
                            return false;
                        }
                    } catch (Throwable v10) {
                        v4_1 = System.currentTimeMillis() - v16;
                        int v8 = AppLog.w();
                        AppLog.onImageSample(url, v4_1, v12[0], v8, v11[0], v10);
                        AppLog.x();
                        int v4_2 = ((v10 instanceof SocketException)) || ((v10 instanceof IOException)) || ((v10 instanceof SocketTimeoutException)) || ((v10 instanceof HttpResponseException)) ? 1 : 0;
                        if (v4_2 == 0) {
                            throw v10;
                        }

                        if (context == null) {
                            return false;
                        }

                        AppLog.u();
                        if (!NetworkUtils.isNetworkAvailable(context)) {
                            return false;
                        }

                        NetworkType networkType = NetworkUtils.getNetworkType(context);
                        v4_2 = 0;
                        if (networkType != null && networkType != NetworkType.NONE) {
                            v4_2 = networkType.getValue();
                        }

                        AppLog.a(url, v4_2, v8);
                        Logger.v("AppUtil", "failed to load image: " + url + " " + v10);
                        v5 = v13;
                        continue;
                    }
                }
                v14 = NetworkUtils.downloadFile(v2,
                        url,
                        externalImageSaveDir,
                        internalImageSaveDir,
                        cacheFileName,
                        arg25,
                        arg26,
                        taskInfo,
                        imageUrl.headers,
                        v11,
                        v12);
                v4_1 = System.currentTimeMillis() - v16;
                if (v14) {
                    File v6_1 = new File(externalImageSaveDir, cacheFileName);
                    if (!v6_1.isFile()) {
                    } else {
                        long v6_2 = v6_1.length();
                        if (v6_2 <= 0) {
                        } else {
                            BaseAppData.ce.addAndGet(v6_2);
                            if (v12[0] > 0) {
                            } else if (v6_2 >= 2147483647) {
                            } else {
                                v12[0] = ((int) v6_2);
                            }
                        }
                    }
                    AppLog.onImageSample(url, v4_1, ((long) v12[0]), 200, v11[0], null);
                    AppLog.t();
                    if (context == null) {
                        return v14;
                    }

                    if (new Random().nextInt(10) < 3) {
                        int v6_3 = NetworkUtils.getNetworkType(context).getValue();
                        if (v6_3 != 0) {
                            AppLog.a(url, v6_3, v4_1);
                        }
                    }
                    return v14;
                }

                if (taskInfo == null || !taskInfo.a) {
                    AppLog.onImageSample(url, v4_1, ((long) v12[0]), 1, v11[0], null);
                }
                return v14;
            }
        } else {
            v2_1 = false;
        }

        return v2_1;
    }

    public static long a(String arg7, String arg8, Context arg9, JSONObject arg10) {
        return a(arg7, arg8, arg9, true, null, null, arg10);
    }

    public static boolean downloadImage(Context context, int arg11, String arg12,
                                        String arg13, String arg14, String arg15,
                                        String arg16, d arg17, String arg18, TaskInfo taskInfo) throws Throwable {
        return downloadImage(context, arg11, arg12, ImageInfo.extractImageUrlList(arg12, arg13), arg14, arg15, arg16, arg17, arg18, taskInfo);
    }

    public static Response doHttpRequest(String url, List<HttpHeader> headerList) {
        BuffHolder buffer;
        GZIPInputStream gzipInputStream = null;
        URLConnection connection = null;
        Response response = new Response(url);
        response.responseCode = 18;
        if (android.support.design.a.isTextEmpty(url)) {
            return response;
        }

        InputStream inputStream = null;
        try {
            connection = new URL(url).openConnection();
            NetworkUtils.setTimeout(connection);
            Iterator<HttpHeader> iterator = headerList.iterator();
            while (iterator.hasNext()) {
                HttpHeader httpHeader = iterator.next();
                connection.setRequestProperty(httpHeader.name(), httpHeader.value());
            }
            connection.connect();
            response.responseCode = ((HttpURLConnection) connection).getResponseCode();
            String requestUrl = connection.getURL().toString();
            if (!android.support.design.a.isTextEmpty(requestUrl) && !url.equals(requestUrl)) {
                response.requestUrl = requestUrl;
            }

            if (response.responseCode == 200) {
                int contentLength = connection.getContentLength();
                if (contentLength >= 0 && 512000 < contentLength) {
                    response.responseCode = 20;
                    if (connection != null) {
                        try {
                            ((HttpURLConnection) connection).disconnect();
                        } catch (Exception exception) {
                        }
                        return response;
                    } else {
                        return response;
                    }
                }
                inputStream = connection.getInputStream();
                if ("gzip".equalsIgnoreCase(connection.getContentEncoding())) {
                    gzipInputStream = new GZIPInputStream(inputStream);
                }
                buffer = new BuffHolder();
                byte[] buff = new byte[4096];
                do {
                    int readLength = gzipInputStream.read(buff);
                    if (readLength <= 0) {
                        buff = new byte[buffer.length];
                        if (buffer.length > 0) {
                            System.arraycopy(buffer.buff, 0, buff, 0, buffer.length);
                        }
                        response.bytes = buff;
                        response.contentType = connection.getContentType();
                        return response;
                    } else if (readLength >= 0 && readLength >= 0 && readLength <= 4096) {
                        if (readLength != 0) {
                            int newLength = buffer.length + readLength;
                            if (newLength > buffer.buff.length) {
                                byte[] newBuff = new byte[Math.max(buffer.buff.length << 1, newLength)];
                                System.arraycopy(buffer.buff, 0, newBuff, 0, buffer.length);
                                buffer.buff = newBuff;
                            }
                            System.arraycopy(buff, 0, buffer.buff, buffer.length, readLength);
                            buffer.length = newLength;
                        }
                        if (buffer.length <= 512000) {
                            continue;
                        }
                        break;
                    } else {
                        throw new IndexOutOfBoundsException();
                    }
                } while (true);
                response.responseCode = 20;
            }
        } catch (Throwable throwable) {
            response.responseCode = TTUtils.getErrorCode(sContext, throwable);
        } finally {
            if (connection != null) {
                try {
                    ((HttpURLConnection) connection).disconnect();
                } catch (Exception v0_3) {
                }
            }

            if (gzipInputStream != null) {
                try {
                    gzipInputStream.close();
                } catch (Exception e) {

                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {

                }
            }
        }
        return response;
    }

    public static void a(Context arg10, ImageInfo arg11, BaseImageManager arg12, boolean arg13) {
        if (arg11 != null && arg12 != null) {
            try {
                String v9 = arg11.mKey;
                String v0_1 = arg12.getExternalCacheFile(v9);
                String v1 = arg12.getInternalCacheFile(v9);
                File v2 = new File(v0_1);
                File v3 = new File(v1);
                int v0_2 = 0;
                if ((v2.isFile()) || (v3.isFile())) {
                    v0_2 = 1;
                    if (arg13) {
                        arg12.saveImage(arg10, v9, arg11.mUri);
                    }
                }

                boolean v1_1 = NetworkUtils.isNetworkAvailable(arg10);
                if (v0_2 != 0) {
                    return;
                }

                if (!v1_1) {
                    return;
                }

                downloadImage(null, 20971520, arg11.mUri, arg11.mUrlList, arg12.getExternalImageSaveDir(v9), arg12.getInternalImageSaveDir(v9), BaseImageManager.getCacheFileName(v9), null, null);
                if (!arg13) {
                    return;
                }

                arg12.saveImage(arg10, v9, arg11.mUri);
            } catch (Throwable throwable) {
                Logger.d("AppUtil", throwable.getMessage());
            }
        }
    }

    public static AlertDialog a(Context arg10, MediaAppData arg11, String arg12, String arg13, String arg14, JSONObject arg15, long[] arg16) {
        AlertDialog v0_1;
        int v0;
        if (arg10 == null || arg11 == null || (android.support.design.a.isTextEmpty(arg12))) {
            v0_1 = null;
        } else {
            if (android.support.design.a.isTextEmpty(arg12)) {
                v0 = 1;
            } else {
                if (!arg11.downloadWhiteList.isEmpty()) {
                    Iterator v1 = arg11.downloadWhiteList.iterator();
                    do {
                        if (v1.hasNext()) {
                            if (arg12.indexOf((String) v1.next()) < 0) {
                                continue;
                            }
                            v0 = 1;
                            break;
                        }
                        v0 = 0;
                        break;
                    }
                    while (true);
                } else {
                    v0 = 0;
                }
            }

            if (v0 != 0) {
                if (Build.VERSION.SDK_INT < 23) {
                    arg16[0] = a(arg10, arg12, arg13, arg14, arg15);
                } else if ((arg10 instanceof Activity)) {
                    PermissionsManager.getInstance().requestPermission((Activity) arg10, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, new com.ss.android.newmedia.util.b(arg10, arg12, arg13, arg14, arg15, arg16));
                }

                v0_1 = null;
                return v0_1;
            }

            AlertDialog.Builder v7 = com.ss.android.j.b.createDialogBuilder(arg10);
            v7.setTitle(((CharSequence) arg12)).setMessage(com.ss.android.article.browser.R.string.l5);
            v7.setNegativeButton(com.ss.android.article.browser.R.string.label_cancel, null);
            v7.setPositiveButton(com.ss.android.article.browser.R.string.label_confirm, new com.ss.android.newmedia.util.c(arg10, arg12, arg13, arg14, arg15, arg16));
            v0_1 = v7.show();
        }

        return v0_1;
    }

    public static boolean downloadImage(Context arg10, int arg11, String arg12, String arg13, String arg14, String arg15, String arg16, d arg17, TaskInfo arg18) throws Throwable {
        return downloadImage(arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg16, arg18);
    }

    public static void a(Context arg2, ImageInfo arg3, BaseImageManager arg4) {
        Context v0 = arg2 != null ? arg2.getApplicationContext() : null;
        new e(v0, arg3, arg4).start();
    }

    public static void clearWebViewCache(Activity arg5) {
        if (arg5 != null) {
            try {
                long v0_1 = System.currentTimeMillis();
                WebView v2 = new WebView(((Context) arg5));
                v2.clearCache(true);
                v2.destroy();
                Logger.d("AppUtil", "clear webview cache done " + (System.currentTimeMillis() - v0_1));
            } catch (Exception v0) {
            }
        }
    }

    public static long a(String arg10, String arg11, Context arg12, boolean arg13, boolean arg14, boolean arg15, boolean arg16, JSONObject arg17) {
        return a(arg10, arg11, arg12, arg13, null, null, arg14, arg15, arg16, arg17);
    }

    public static boolean a(Context arg10, int arg11, String arg12, List arg13, String arg14, String arg15, String arg16, d arg17, TaskInfo arg18) throws Throwable {
        return b(arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg16, arg18);
    }

    static long a(Context arg7, String arg8, String arg9, String arg10, JSONObject arg11) {
        ArrayList v5;
        String v1 = null;
        if (!android.support.design.a.isTextEmpty(arg9)) {
            v5 = new ArrayList();
            ((List) v5).add(new LegacyHeader("User-Agent", arg9));
        } else {
            v5 = null;
        }

        return a(arg8, v1, arg7, false, arg10, ((List) v5), arg11);
    }

    private static long a(String arg10, String arg11, Context arg12, boolean arg13, String arg14, List arg15, JSONObject arg16) {
        return a(arg10, arg11, arg12, arg13, arg14, arg15, true, true, false, arg16);
    }

    private static long a(String arg12, String arg13, Context arg14, boolean arg15, String arg16, List arg17, boolean arg18, boolean arg19, boolean arg20, JSONObject arg21) {
        long v2_1;
        if (!android.support.design.a.isTextEmpty(arg12) && arg14 != null) {
            if (arg14 == null || arg21 == null) {

            } else {
                try {
                    String v5 = arg21.optString("label");
                    JSONObject v10 = arg21.optJSONObject("ext_json");
                    if (!android.support.design.a.isTextEmpty(v5)) {
                        MobClickCombiner.onEvent(arg14, "wap_stat", "app_download", v5, 0, 0, v10);
                    } else {
                    }
                } catch (Exception v2) {
                }
            }

            if (BaseAppData.inst().allowInsideDownloadManager()) {
                if (arg14 == null) {
                    v2_1 = -1;
                } else {
                    LinkedHashMap v8 = new LinkedHashMap();
                    if (arg17 != null) {
                        Iterator v3 = arg17.iterator();
                        while (v3.hasNext()) {
                            Object v2_2 = v3.next();
                            ((Map) v8).put(((HttpHeader) v2_2).name(), ((HttpHeader) v2_2).value());
                        }
                    }

                    v2_1 = DownloadAdapterProxy.inst().addDownloadTask(arg12, arg13, arg15, arg14, arg16, ((Map) v8), arg18, arg19, arg20);
                }

                if (v2_1 >= 0) {
                    return v2_1;
                }
            } else {
                v2_1 = android.support.design.a.a(arg12, arg13, arg15, arg14, arg16, arg17, arg18);
                if (v2_1 < 0) {
                    return -1;
                }

                return v2_1;
            }
            return -1;
        }

        return -1;
    }

    private static String a(String arg4) {
        String v1 = "";
        if (!android.support.design.a.isTextEmpty(arg4)) {
            try {
                String v0_1 = new String(Base64.decode(arg4, 0), "utf-8");
                return v0_1;
            } catch (Throwable v0) {
            }
        }

        return v1;
    }

    public static boolean b(Context arg1, String arg2) {
        return AdsAppBaseActivity.openUrl(arg1, arg2, null);
    }

    public static boolean b(Context arg6, String arg7, String arg8) {
        boolean v0 = true;
        if ((android.support.design.a.isTextEmpty(arg7)) || !ToolUtils.isAppInstalled(arg6, arg7)) {
            if (!android.support.design.a.isTextEmpty(arg8)) {
                Uri v1 = Uri.parse(arg8);
                String v2 = v1.getScheme();
                if (!ToolUtils.isInstalledApp(arg6, new Intent("com.ss.android.sdk." + v2))) {
                    Intent v3 = new Intent();
                    if (AdsAppBaseActivity.c(v2)) {
                        v3.putExtra("is_from_self", true);
                    }

                    v3.setData(v1);
                    if (ToolUtils.isInstalledApp(arg6, v3)) {
                        return v0;
                    }
                } else {
                    return v0;
                }
            }

            v0 = false;
        }

        return v0;
    }

    private static boolean b(Context arg15, int arg16, String arg17, List arg18, String arg19, String arg20, String arg21, d arg22, String arg23, TaskInfo arg24) throws Throwable {
        boolean v4_2 = false;
        boolean v2_1;
        int v2 = arg16 <= 0 ? 10485760 : arg16;
        if (arg18 != null && !arg18.isEmpty()) {
            if (arg15 == null) {
                arg15 = sContext;
            }

            Iterator v14 = arg18.iterator();
            int v4 = 0;
            while (true) {
                if (!v14.hasNext()) {
                } else {
                    Object v3 = v14.next();
                    if (v3 == null) {
                        continue;
                    }

                    String v3_1 = a(((String) v3));
                    if (android.support.design.a.isTextEmpty(v3_1)) {
                        continue;
                    }

                    int v13 = v4 + 1;
                    if (v13 > 3) {
                        v2_1 = false;
                        return v2_1;
                    }

                    if (Logger.debug()) {
                        Logger.v("AppUtil", "try video: " + arg17 + " " + v3_1);
                    }

                    String[] v11 = new String[1];
                    int[] v12 = new int[1];
                    if (arg15 != null) {
                        if (!NetworkUtils.isNetworkAvailable(arg15)) {
                            return false;
                        }


                    }
                    v4_2 = NetworkUtils.downloadFile(v2, v3_1, arg19, arg20, arg21, arg22, arg23, arg24, null, v11, v12);
                    if (v4_2) {
                    } else {
                        return v4_2;
                    }

                    try {
                        File v5 = new File(arg19, arg21);
                        if (!v5.isFile()) {
                            break;
                        }

                        long v6 = v5.length();
                        if (v6 <= 0) {
                            break;
                        }

                        BaseAppData.ce.addAndGet(v6);
                        if (v12[0] > 0) {
                            break;
                        }

                        if (v6 >= 2147483647) {
                            break;
                        }

                        v12[0] = ((int) v6);
                        break;
                    } catch (Exception v4_1) {
                        AppLog.x();
                        int v5_1 = ((v4_1 instanceof SocketException)) || ((v4_1 instanceof IOException)) || ((v4_1 instanceof SocketTimeoutException)) || ((v4_1 instanceof HttpResponseException)) ? 1 : 0;
                        if (v5_1 == 0) {
                            break;
                        }

                        if (arg15 == null) {
                            return false;
                        }

                        if (!NetworkUtils.isNetworkAvailable(arg15)) {
                            return false;
                        }

                        Logger.v("AppUtil", "failed to load video: " + v3_1 + " " + v4_1);
                        v4 = v13;
                        continue;
                    }
                }

                if (arg15 == null) {
                    return v4_2;
                }

                return v4_2;
            }

            v2_1 = false;
        } else {
            v2_1 = false;
        }
        return v2_1;
    }

    public static boolean c(Context arg1, String arg2, String arg3) {
        return AdsAppBaseActivity.openUrl(arg1, arg2, arg3);
    }
}

